<template>
  <view class="container">
    <view class="section" v-if="loading">
      <text>加载中...</text>
    </view>
    <view v-else>
      <view class="section header">
        <view class="row">
          <text class="label">订单状态</text>
          <text class="value status">{{ getStatusText(order.status) }}</text>
        </view>
        <view class="row">
          <text class="label">下单时间</text>
          <text class="value">{{ formatDate(order.orderTime) }}</text>
        </view>
      </view>
      <view class="section">
        <view class="section-title">收货信息</view>
        <view class="row">
          <text class="label">收货人</text>
          <text class="value">{{ order.address.name || recinfo.name }}</text>
        </view>
        <view class="row">
          <text class="label">联系电话</text>
          <text class="value">{{ order.address.phone || recinfo.phone }}</text>
        </view>
        <view class="row">
          <text class="label">收货地址</text>
          <text class="value"
            >{{ order.address.region || recinfo.region }}-{{
              order.address.address || recinfo.address
            }}
          </text>
        </view>
      </view>

      <!-- 退货信息 (仅在退货状态时显示) -->
      <view class="section" v-if="shouldShowReturnInfo(order.status)">
        <view class="section-title">退货信息</view>
        <view class="row" v-if="order.returnReason">
          <text class="label">退货原因</text>
          <text class="value">{{ order.returnReason }}</text>
        </view>
        <view class="row" v-if="order.adminReturnRemark">
          <text class="label">管理员备注</text>
          <text class="value remark-text">{{
            formatRemark(order.adminReturnRemark)
          }}</text>
        </view>
        <view class="row" v-if="order.returnRequestTime">
          <text class="label">申请退货时间</text>
          <text class="value">{{ formatDate(order.returnRequestTime) }}</text>
        </view>
        <view class="row" v-if="order.returnProcessTime">
          <text class="label">处理时间</text>
          <text class="value">{{ formatDate(order.returnProcessTime) }}</text>
        </view>
      </view>

      <!-- 发票信息 (在已完成订单或已退货订单且剩余金额>0时显示) -->
      <view class="section" v-if="shouldShowInvoiceInfo()">
        <view class="section-title">发票信息</view>

        <!-- 发票抬头信息 -->
        <view v-if="invoiceInfo">
          <view class="row">
            <text class="label">发票抬头</text>
            <text class="value">{{
              invoiceInfo.invoiceTitle || "未填写"
            }}</text>
          </view>
          <view class="row">
            <text class="label">单位税号</text>
            <text class="value">{{
              invoiceInfo.invoiceTaxNumber || "未填写"
            }}</text>
          </view>
          <view class="row" v-if="invoiceInfo.invoiceAddress">
            <text class="label">注册地址</text>
            <text class="value">{{ invoiceInfo.invoiceAddress }}</text>
          </view>
          <view class="row" v-if="invoiceInfo.invoicePhone">
            <text class="label">注册电话</text>
            <text class="value">{{ invoiceInfo.invoicePhone }}</text>
          </view>
          <view class="row" v-if="invoiceInfo.invoiceBank">
            <text class="label">开户银行</text>
            <text class="value">{{ invoiceInfo.invoiceBank }}</text>
          </view>
          <view class="row" v-if="invoiceInfo.invoiceBankAccount">
            <text class="label">银行账户</text>
            <text class="value">{{ invoiceInfo.invoiceBankAccount }}</text>
          </view>
          <view class="row" v-if="invoiceInfo.invoiceRemark">
            <text class="label">发票备注</text>
            <text class="value">{{ invoiceInfo.invoiceRemark }}</text>
          </view>
        </view>

        <!-- 发票操作按钮 -->
        <view class="invoice-actions">
          <view class="action-btn primary" @tap="addInvoiceInfo">
            <text>{{
              invoiceInfo && invoiceInfo.invoiceTitle
                ? "修改发票抬头"
                : "添加发票抬头"
            }}</text>
          </view>
          <view class="action-btn secondary" @tap="viewInvoice">
            <text>查看发票</text>
          </view>
        </view>
      </view>

      <view class="section">
        <view class="section-title">{{
          shouldShowReturnInfo(order.status) ? "退货商品信息" : "商品信息"
        }}</view>
        <view
          class="product"
          v-for="(item, idx) in getDisplayItems()"
          :key="idx"
        >
          <image class="thumb" :src="getFirstImage(item.product.pImgUrl)" />
          <view class="info">
            <view class="name">商品名称: {{ item.product.pName }}</view>
            <view class="meta"
              >数量：{{ item.displayQuantity || item.pNumber }} 单价：￥{{
                item.pPrice
              }}</view
            >
            <view
              class="return-info"
              v-if="shouldShowReturnInfo(order.status) && item.isReturnItem"
            >
              <text class="return-label">退货商品</text>
            </view>
          </view>
        </view>
      </view>

      <view class="section total">
        <text>{{ getTotalLabel() }}￥{{ getDisplayTotal() | toFixed}}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getOrderDetail, getInvoiceInfo } from "@/common/api/orderList.js";
import { getFirstImage } from "@/common/utils/index.js";
import {
  add,
  subtract,
  multiply,
  safeNumber,
  calculateOrderTotal,
} from "@/common/utils/precision.js";

export default {
  data() {
    return {
      getFirstImage,
      id: "",
      order: {},
      loading: true,
      defaultImg: "../../../static/img/noorder.png",
      invoiceInfo: null,
      statusText: {
        PENDING_SHIP: "等待商家发货",
        SHIPPED: "商家已发货",
        PENDING_PAYMENT: "待付款",
        COMPLETED: "交易已完成",
        RETURN_REQUESTED: "退货申请中",
        RETURN_APPROVED: "退货已同意",
        RETURN_REJECTED: "退货被拒绝",
        RETURNED: "已退货",
        CANCELLED: "订单已取消",
        PENDING: "待确认",
        QUOTED: "已报价",
        CONFIRMED: "已确认",
        CANCELLED: "已取消",
      },
      recinfo: {},
    };
  },
  onLoad(query) {
    this.id = query?.id || "";
    if (!this.id) {
      uni.showToast({ title: "缺少订单ID", icon: "none" });
      this.loading = false;
      return;
    }
    this.fetchDetail();
  },
  onShow() {
    uni.getStorage({
      key: "selectAddress",
      success: (e) => {
        this.recinfo = e.data;
        uni.removeStorage({
          key: "selectAddress",
        });
      },
    });
  },
  filters: {
    toFixed: function (x) {
      return parseFloat(x).toFixed(2);
    },
  },
  methods: {
    async fetchDetail() {
      try {
        uni.showLoading({ title: "加载中..." });
        const res = await getOrderDetail(this.id);

        // 兼容多种响应结构：统一拦截器包装可能是 { data: { ...订单详情 } } 或直接返回订单详情
        let detail = null;
        if (res?.data?.data) {
          detail = res.data.data;
        } else if (res?.data) {
          detail = res.data;
        } else {
          detail = res;
        }

        this.order = detail || {};

        // 如果是已完成订单、退货同意或已退货订单，加载发票信息
        if (
          detail &&
          (detail.status === "COMPLETED" ||
            detail.status === "RETURN_APPROVED" ||
            detail.status === "RETURNED")
        ) {
          this.loadInvoiceInfo();
        }
      } catch (e) {
        uni.showToast({ title: "加载失败", icon: "none" });
      } finally {
        this.loading = false;
        uni.hideLoading();
      }
    },
    
    // 加载发票信息
    async loadInvoiceInfo() {
      try {
        const res = await getInvoiceInfo(this.id);
        if (res.data && res.data.ok && res.data.data.invoiceInfo) {
          this.invoiceInfo = res.data.data.invoiceInfo;
        }
      } catch (error) {}
    },
    getStatusText(s) {
      return this.statusText[s] || s || "未知状态";
    },
    formatDate(v) {
      if (!v) return "";
      const d = new Date(v);
      return (
        d.toLocaleDateString("zh-CN") +
        " " +
        d.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" })
      );
    },
    // 格式化备注文本，处理特殊字符和换行
    formatRemark(remark) {
      if (!remark) return "";

      // 如果包含HTML标签或看起来像JSON数据，先清理
      let cleanText = remark;

      // 移除HTML标签
      cleanText = cleanText.replace(/<[^>]*>/g, "");

      // 如果是JSON格式，尝试解析
      try {
        if (
          cleanText.trim().startsWith("{") ||
          cleanText.trim().startsWith("[")
        ) {
          const parsed = JSON.parse(cleanText);
          // 如果是对象，尝试提取有意义的文本
          if (typeof parsed === "object") {
            cleanText =
              parsed.message ||
              parsed.content ||
              parsed.text ||
              JSON.stringify(parsed, null, 2);
          }
        }
      } catch (e) {
        // 如果不是有效JSON，继续使用原文本
      }

      // 处理换行符和特殊字符
      cleanText = cleanText
        .replace(/\\n/g, "\n") // 处理转义的换行符
        .replace(/\\r/g, "\r") // 处理转义的回车符
        .replace(/\\t/g, "  ") // 处理转义的制表符
        .replace(/\\\\/g, "\\") // 处理转义的反斜杠
        .replace(/\\"/g, '"') // 处理转义的引号
        .trim();

      return cleanText;
    },
    // 判断是否显示退货信息
    shouldShowReturnInfo(status) {
      const returnStatuses = [
        "RETURN_REQUESTED",
        "RETURN_APPROVED",
        "RETURN_REJECTED",
        "RETURNED",
      ];
      return returnStatuses.includes(status);
    },

    // 判断是否显示发票信息
    shouldShowInvoiceInfo() {
      if (!this.order) return false;

      // 已完成订单总是显示发票信息
      if (
        this.order.status === "COMPLETED" ||
        this.order.status === "RETURN_APPROVED"
      ) {
        return true;
      }

      // 已退货订单也显示发票信息（无论剩余金额是否大于0）
      if (this.order.status === "RETURNED") {
        return true;
      }

      return false;
    },

    // 计算剩余金额（总金额 - 退货金额）
    calculateRemainingAmount() {
      if (!this.order) return 0;

      const originalTotal = safeNumber(this.order.orderPrice, 0);
      const returnAmount = this.calculateReturnAmount();
      const remainingAmount = subtract(originalTotal, returnAmount, 2);

      return Math.max(0, remainingAmount);
    },

    // 获取要显示的商品列表
    getDisplayItems() {
      if (!this.order || !this.order.orderItems) return [];

      // 如果不是退货状态，显示所有商品
      if (!this.shouldShowReturnInfo(this.order.status)) {
        return this.order.orderItems;
      }

      // 如果是退货状态，需要解析退货商品信息
      try {
        // 尝试解析 remark 字段中的退货商品信息
        if (this.order.remark) {
          const returnItems = JSON.parse(this.order.remark);

          // 如果成功解析出退货商品信息，说明是部分退货
          if (Array.isArray(returnItems) && returnItems.length > 0) {
            return this.order.orderItems
              .filter((orderItem) => {
                // 只显示申请退货的商品
                return returnItems.some(
                  (returnItem) => returnItem.orderItemId === orderItem.id
                );
              })
              .map((orderItem) => {
                // 找到对应的退货信息
                const returnItem = returnItems.find(
                  (ri) => ri.orderItemId === orderItem.id
                );
                return {
                  ...orderItem,
                  displayQuantity: returnItem
                    ? returnItem.returnQuantity
                    : orderItem.pNumber,
                  isReturnItem: true,
                };
              });
          }
        }

        // 如果没有具体的退货商品信息或解析失败，说明是整单退货，显示所有商品
        return this.order.orderItems.map((item) => ({
          ...item,
          isReturnItem: true,
        }));
      } catch (error) {
        console.warn("解析退货商品信息失败:", error);
        // 解析失败时，显示所有商品（整单退货）
        return this.order.orderItems.map((item) => ({
          ...item,
          isReturnItem: true,
        }));
      }
    },

    // 获取要显示的总金额
    getDisplayTotal() {
      if (!this.order) return "0.00";

      // 如果不是退货状态，显示订单总金额
      if (!this.shouldShowReturnInfo(this.order.status)) {
        return this.order.orderPrice || "0.00";
      }

      const originalTotal = safeNumber(this.order.orderPrice, 0);

      // 根据退货状态决定显示逻辑
      if (this.order.status === "RETURN_REQUESTED") {
        // 申请退货状态：显示申请退货的商品金额 - 使用精度工具
        const displayItems = this.getDisplayItems();
        if (!displayItems || displayItems.length === 0) {
          return "0.00";
        }

        const returnTotal = calculateOrderTotal(
          displayItems.map((item) => ({
            quantity: safeNumber(item.displayQuantity || item.pNumber, 0),
            price: safeNumber(item.pPrice, 0),
          })),
          2
        );
        console.log("申请退货状态：", returnTotal);
        return returnTotal
      } else if (
        this.order.status === "RETURN_APPROVED" ||
        this.order.status === "RETURNED"
      ) {
        // 退货同意/已退货状态：显示实际退货商品的金额 - 使用精度工具
        const returnAmount = this.calculateReturnAmount();
        return returnAmount;
      } else {
        // 其他退货相关状态（如RETURN_REJECTED）：显示原订单总金额
        return originalTotal
      }
    },

    // 计算退货商品的金额
    calculateReturnAmount() {
      if (!this.order || !this.order.orderItems) return 0;

      try {
        // 尝试解析 remark 字段中的退货商品信息
        if (this.order.remark) {
          const returnItems = JSON.parse(this.order.remark);

          // 如果成功解析出退货商品信息，说明是部分退货 - 使用精度工具
          if (Array.isArray(returnItems) && returnItems.length > 0) {
            const filteredItems = this.order.orderItems
              .filter((orderItem) => {
                return returnItems.some(
                  (returnItem) => returnItem.orderItemId === orderItem.id
                );
              })
              .map((orderItem) => {
                const returnItem = returnItems.find(
                  (ri) => ri.orderItemId === orderItem.id
                );
                const quantity = returnItem
                  ? safeNumber(returnItem.returnQuantity, 0)
                  : safeNumber(orderItem.pNumber, 0);
                const price = safeNumber(orderItem.pPrice, 0);
                return { quantity, price };
              });

            return calculateOrderTotal(filteredItems, 2);
          }
        }

        // 如果没有具体的退货商品信息，说明是整单退货 - 使用精度工具
        return calculateOrderTotal(
          this.order.orderItems.map((item) => ({
            quantity: safeNumber(item.pNumber, 0),
            price: safeNumber(item.pPrice, 0),
          })),
          2
        );
      } catch (error) {
        console.warn("计算退货金额失败:", error);
        // 解析失败时，按整单退货计算 - 使用精度工具
        return calculateOrderTotal(
          this.order.orderItems.map((item) => ({
            quantity: safeNumber(item.pNumber, 0),
            price: safeNumber(item.pPrice, 0),
          })),
          2
        );
      }
    },

    // 获取金额标签
    getTotalLabel() {
      if (!this.order) return "合计：";

      switch (this.order.status) {
        case "RETURN_REQUESTED":
          return "退货金额：";
        case "RETURN_APPROVED":
        case "RETURNED":
          return "退货金额：";
        case "RETURN_REJECTED":
          return "订单金额：";
        default:
          return "合计：";
      }
    },

    // 添加发票抬头
    addInvoiceInfo() {
      uni.navigateTo({
        url: `/pages/user/invoice/invoice?orderId=${this.id}`,
      });
    },

    // 查看发票
    async viewInvoice() {
      try {
        uni.showLoading({
          title: "加载中...",
        });

        const res = await getInvoiceInfo(this.id);

        // 处理多层响应结构
        let invoiceImageUrl = null;
        if (res?.data?.data?.invoiceImageUrl) {
          invoiceImageUrl = res.data.data.invoiceImageUrl;
        } else if (res?.data?.invoiceImageUrl) {
          invoiceImageUrl = res.data.invoiceImageUrl;
        } else if (res?.invoiceImageUrl) {
          invoiceImageUrl = res.invoiceImageUrl;
        }

        uni.hideLoading(); // 先隐藏loading

        if (invoiceImageUrl) {
          // 有发票图片，跳转到发票查看页面
          uni.navigateTo({
            url: `/pages/user/invoice_view/invoice_view?orderId=${
              this.id
            }&imageUrl=${encodeURIComponent(invoiceImageUrl)}`,
          });
        } else {
          // 没有发票图片
          uni.showToast({
            title: "暂无发票图片",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading(); // 确保隐藏loading
        uni.showToast({
          title: "获取发票信息失败",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss">
.container {
  padding: 20upx;
}
.section {
  background: #fff;
  border-radius: 10upx;
  padding: 20upx;
  margin-bottom: 20upx;
}
.section-title {
  font-weight: 600;
  margin-bottom: 10upx;
}
.row {
  display: flex;
  justify-content: space-between;
  margin: 6upx 0;
}
.label {
  color: #888;
}
.value {
  color: #333;
}

.remark-text {
  line-height: 1.6;
  word-wrap: break-word;
  word-break: break-all;
  white-space: pre-wrap; /* 保持换行符和空格 */
}
.status {
  color: #ec652f;
}
.product {
  display: flex;
  gap: 20upx;
  padding: 10upx 0;
  align-items: center;
}
.thumb {
  width: 120upx;
  height: 120upx;
  border-radius: 8upx;
  background: #f5f5f5;
}
.info {
  flex: 1;
}
.name {
  font-weight: 600;
  margin-bottom: 6upx;
}
.meta {
  color: #666;
  font-size: 24upx;
}

.return-info {
  margin-top: 8upx;

  .return-label {
    background-color: #ff6b35;
    color: #fff;
    font-size: 20upx;
    padding: 4upx 8upx;
    border-radius: 6upx;
  }
}
.total {
  text-align: right;
  font-size: 28upx;
  font-weight: 600;
}

.invoice-actions {
  display: flex;
  gap: 20upx;
  margin-top: 20upx;
  padding: 0 10upx;
}

.action-btn {
  flex: 1;
  height: 60upx;
  border-radius: 30upx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24upx;

  &.primary {
    background-color: #007aff;
    color: #fff;
  }

  &.secondary {
    background-color: #f8f8f8;
    color: #666;
    border: 1upx solid #e1e1e1;
  }
}
</style>
